package com.wynet.shopsapp.service.impl;

import com.wynet.shopsapp.dao.OssLogDao;
import com.wynet.shopsapp.entity.OssLog;
import com.wynet.shopsapp.service.intf.OssLogService;
import com.wynet.shopsapp.util.AliOssUtil;
import com.wynet.shopsapp.util.DateUtil;
import com.wynet.shopsapp.util.FileUtil;
import com.wynet.shopsapp.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Service
public class OssLogServiceImpl implements OssLogService {
    @Resource
    private OssLogDao dao;

    @Override
    public R uploadImg(MultipartFile file) {
        //1.验证
        if(!file.isEmpty()){
            try {
                //2.获取文件内容
                byte[] data=file.getBytes();
                //3.获取上传文件名 保持长度，名称唯一
                String name= FileUtil.rename(file.getOriginalFilename());
                Date date= DateUtil.getYear(3);
                //4.上传文件内容到Oss
                String url= AliOssUtil.upload(data,name,date);

                //5.验证上传是否成功
                if(StringUtils.hasLength(url)){

                    //6.记录数据到数据库
                    dao.insert(new OssLog(name,url,1,date));

                    //返回 记得要返回 图片的访问地址
                    return R.ok(url);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("亲，图片上传失败，请检查图片内容！");
    }

    @Override
    public R all() {
        return R.ok(dao.selectList(null));
    }
}
